import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userinfo: {},
		token: ''
	},
	mutations: {
		// token => vuex
		setToken(state, token) {
			if (token) {
				state.token = token
				uni.setStorageSync('token', token)
			} else {
				let token = uni.getStorageSync('token')
				this.commit('setToken', token)
			}
		},
		// userinfo => vuex
		userLogin(state, user) {
			if (user) {
				state.userinfo = user
				uni.setStorageSync('userinfo', JSON.stringify(user))
			} else {
				let user = JSON.parse(uni.getStorageSync('userinfo'))
				this.commit('userLogin', user)
			}
		},
		// vuex clear
		userLogout(state) {
			state.userinfo = ''
			state.token = ''
			uni.removeStorageSync('userinfo')
			uni.removeStorageSync('token')
		}
	}
})

export default store
